<template>
  <el-container>
    <el-header>
      <div>
        <el-form :model="search" ref="queryForm" :inline="true">
          <el-form-item label="名称" prop="name">
            <el-input v-model="search.name" placeholder="名称" clearable />
          </el-form-item>
          <el-form-item label="Token" prop="token">
            <el-input v-model="search.token" placeholder="Token" clearable />
          </el-form-item>

          <el-form-item>
            <el-button-group>
              <el-button type="primary" icon="el-icon-search" @click="upsearch"> 查询 </el-button>
            </el-button-group>
          </el-form-item>
        </el-form>
      </div>
    </el-header>
    <el-header>
      <div class="left-panel">
        <el-button type="primary" icon="el-icon-plus" @click="add">创建令牌</el-button>
      </div>
    </el-header>
    <el-main class="nopadding">
      <scTable
        ref="table"
        tableName="listCustomColumn"
        :apiObj="apiObj"
        :params="search"
        :column="column"
        row-key="id"
        @selection-change="selectionChange"
        stripe
      >
        <el-table-column type="selection" width="50"></el-table-column>
        <!-- 是否启用/禁用 -->
        <template #disableoperator="scope">
          <el-switch v-model="scope.row.disabled" class="ml-2" @change="disableChangeHandle(scope.row)" />
        </template>

        <!-- 已用额度 -->
        <template #UsedQuotaoperator="scope">
          <span> {{ moneyFormat(scope.row.usedQuota) }}</span>
        </template>

        <!-- 剩余额度 -->
        <template #UnUseQutooperator="scope">
          <span v-if="scope.row.unlimitedQuota">不限制</span>
          <span v-else>{{ moneyFormat(scope.row.unUsedQuota) }}</span>
        </template>

        <!-- 过期时间 -->
        <template #Expireoperator="scope">
          <span v-if="scope.row.unlimitedExpired">不过期</span>
          <span v-else>{{ dateFormat(scope.row.expiredTime) }}</span>
        </template>

        <template #operator="scope">
          <el-dropdown>
            <span class="el-dropdown-link">
              操作
              <el-icon class="el-icon-right"><ArrowDown /></el-icon>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="copy" @click="table_copy(scope.row)">复制Key</el-dropdown-item>

                <el-dropdown-item command="show" @click="table_show(scope.row)">查看</el-dropdown-item>
                <el-dropdown-item command="edit" @click="table_edit(scope.row)">编辑</el-dropdown-item>
                <el-dropdown-item command="del" @click="table_del(scope.row)">删除</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </scTable>
    </el-main>
  </el-container>

  <save-dialog v-if="dialog.save" ref="saveDialog" @success="handleSaveSuccess" @closed="dialog.save = false"></save-dialog>
</template>

<script>
import { ArrowDown } from '@element-plus/icons-vue';
import saveDialog from './save';

export default {
  name: 'AITokenManage',
  components: {
    saveDialog,
    ArrowDown,
  },
  data() {
    return {
      dialog: {
        save: false,
      },
      apiObj: this.$API.aiToken.page,
      selection: [],
      search: {
        name: '',
        token: '',
      },
      column: [
        {
          label: '名称',
          prop: 'name',
          width: '150',
        },
        {
          label: '是否禁用',
          prop: 'disableoperator',
          width: '100',
        },
        {
          label: '已用额度',
          prop: 'UsedQuotaoperator',
          width: '100',
        },
        {
          label: '剩余额度',
          prop: 'UnUseQutooperator',
          width: '100',
        },
        {
          label: '创建时间',
          prop: 'creationTime',
          width: '150',
        },
        {
          label: '最近使用时间',
          prop: 'accessedTime',
          width: '150',
        },
        {
          label: '过期时间',
          prop: 'Expireoperator',
          width: '150',
        },
        {
          label: '操作',
          prop: 'operator',
          width: '170',
          fixed: 'right',
          align: 'right',
        },
      ],
    };
  },
  computed: {
    dateFormat() {
      return function (row) {
        let time = new Date(row); // row 表示一行数据, createdTime 表示要格式化的字段名称
        if (!time) {
          return '';
        }
        let year = time.getFullYear();
        let month = this.dateIfAddZero(time.getMonth() + 1);
        let day = this.dateIfAddZero(time.getDate());
        return year + '-' + month + '-' + day + ' ';
      };
    },

    moneyFormat() {
      return function (row) {
        if (row == undefined) return '';
        // 计算金额
        return '$' + (row / 500000).toFixed(6);
      };
    },
  },
  methods: {
    dateIfAddZero(time) {
      return time < 10 ? '0' + time : time;
    },
    //添加
    add() {
      this.dialog.save = true;
      this.$nextTick(() => {
        this.$refs.saveDialog.open();
      });
    },

    tableHandleCommand(row, action) {
      console.log(row, action);
    },
    /**
     * 复制key
     * @param row 数据
     */
    table_copy(row) {
      var that = this;
      this.$nextTick(() => {
        const textarea = document.createElement('textarea');
        textarea.value = row.key;
        document.body.appendChild(textarea);
        textarea.select();
        document.execCommand('Copy');
        document.body.removeChild(textarea);
        that.$message.success('已复制到剪切板');
      });
    },
    //编辑
    table_edit(row) {
      this.dialog.save = true;
      this.$nextTick(() => {
        this.$refs.saveDialog.open('edit').setData(row);
      });
    },
    //查看
    table_show(row) {
      this.dialog.save = true;
      this.$nextTick(() => {
        this.$refs.saveDialog.open('show').setData(row);
      });
    },

    //删除
    async table_del(row) {
      var res = await this.$API.aiToken.remove.post(row.id);
      if (res.code == 200) {
        this.$refs.table.refresh();
        this.$message.success('删除成功');
      } else {
        this.$alert(res.message, '提示', { type: 'error' });
      }
    },

    /**
     * 表格选择后回调事件
     * @param selection
     */
    selectionChange(selection) {
      this.selection = selection;
    },
    //搜索
    upsearch() {
      this.$refs.table.upData(this.search);
    },
    /**
     * 本地更新数据
     * @param data
     * @param mode
     */
    handleSaveSuccess(data, mode) {
      if (mode == 'add') {
        this.$refs.table.refresh();
      } else if (mode == 'edit') {
        this.$refs.table.refresh();
      }
    },

    /**
     * 禁用状态 切换事件
     * @param currentValue
     * @param oldValue
     */
    async disableChangeHandle(currentValue) {
      var res = await this.$API.aiToken.updateDisable.post({
        id: currentValue.id,
        status: currentValue.disabled,
      });
      if (res.code == 200) {
        this.$refs.table.refresh();
        this.$message.success('操作成功');
      } else {
        this.$alert(res.message, '提示', { type: 'error' });
      }
    },
  },
};
</script>

<style>
.query-select {
  max-width: 100px;
}

.el-dropdown-link {
  cursor: pointer;
  color: var(--el-color-primary);
  display: flex;
  align-items: center;
}
</style>
